package pl.factat.gfk;

import java.awt.image.BufferedImage;

/**
 * Created with IntelliJ IDEA.
 * User: adam
 * Date: 08.01.13
 * Time: 19:30
 * Class for skewing image.
 */
public class ResizeProcessor extends ImageProcessor {
    //private int x0, y0, x1, y1, x2, y2, x3, y3; // left-upper corner, left-bottom corner, right-bottom corner, right-upper corner
    private int width, height;

    BufferedImage src = null;

    public void setNewSize(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public BufferedImage process(BufferedImage image) {
        if ((width < 1 || height < 1) && (image != null)) {
            // Nothing to do.
            return null;
        }
        this.src = image;
        double xratio = (double) src.getWidth() / (double) width;
        double yratio = (double) src.getHeight() / (double) height;
        BufferedImage tmp = new BufferedImage((int) Math.ceil((double) src.getWidth() / xratio), (int) Math.ceil((double) src.getHeight() / yratio), BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < tmp.getWidth()-1; ++x) {
            for (int y = 0; y < tmp.getHeight()-1; ++y) {
                double tmpx = (double) x * xratio;
                double tmpy = (double) y * yratio;
                int rgbx, rgby;
                    RGBPoint ne, nw, se, sw, out;

                    rgbx = (int) Math.floor(tmpx);
                    rgby = (int) Math.floor(tmpy);
                    nw = RGBPoint.getPointFromInt(src.getRGB(rgbx, rgby));

                    rgbx = (int) Math.ceil(tmpx);
                    rgby = (int) Math.floor(tmpy);
                    if (rgbx >= src.getWidth()) --rgbx;
                    ne = RGBPoint.getPointFromInt(src.getRGB(rgbx, rgby));

                    rgbx = (int) Math.floor(tmpx);
                    rgby = (int) Math.ceil(tmpy);
                    if (rgby > src.getHeight()) --rgby;
                    sw = RGBPoint.getPointFromInt(src.getRGB(rgbx, rgby));

                    rgbx = (int) Math.ceil(tmpx);
                    rgby = (int) Math.ceil(tmpy);
                    if (rgby >= src.getHeight()) --rgby;
                    if (rgbx >= src.getWidth()) --rgbx;
                    se = RGBPoint.getPointFromInt(src.getRGB(rgbx, rgby));

                    out = bilinearInterpolation(xratio, yratio, nw, ne, sw, se);
                    tmp.setRGB(x, y, RGBPoint.getIntFromPoint(out));
            }
        }
        return tmp;
    }
}
